/**
 * Shop Filter Functions
 * 商店页面筛选功能
 * 
 * @package WP Bootstrap Woo
 */

(function($) {
    'use strict';

    const ShopFilter = {
        init: function() {
            this.setupPriceFilter();
            this.setupCategoryFilter();
            this.setupSortFilter();
            this.setupViewToggle();
            this.setupLoadMore();
            this.setupFilterToggle();
        },

        // 价格筛选
        setupPriceFilter: function() {
            const $priceSlider = $('.price-range-slider');
            if (!$priceSlider.length) return;

            const $minInput = $('.min-input');
            const $maxInput = $('.max-input');
            const $minRange = $('.min-range');
            const $maxRange = $('.max-range');
            const $progress = $('.price-progress');

            // 更新进度条
            function updateProgress() {
                const minVal = parseInt($minRange.val());
                const maxVal = parseInt($maxRange.val());
                const min = parseInt($minRange.attr('min'));
                const max = parseInt($minRange.attr('max'));

                const leftPercent = ((minVal - min) / (max - min)) * 100;
                const rightPercent = ((maxVal - min) / (max - min)) * 100;

                $progress.css({
                    'left': leftPercent + '%',
                    'right': (100 - rightPercent) + '%'
                });
            }

            // 滑块事件
            $minRange.on('input', function() {
                const minVal = parseInt($(this).val());
                const maxVal = parseInt($maxRange.val());

                if (minVal >= maxVal) {
                    $(this).val(maxVal - 1);
                }

                $minInput.val($(this).val());
                updateProgress();
            });

            $maxRange.on('input', function() {
                const maxVal = parseInt($(this).val());
                const minVal = parseInt($minRange.val());

                if (maxVal <= minVal) {
                    $(this).val(minVal + 1);
                }

                $maxInput.val($(this).val());
                updateProgress();
            });

            // 输入框事件
            $minInput.on('input', function() {
                const value = Math.min(parseInt($(this).val()), parseInt($maxInput.val()) - 1);
                $(this).val(value);
                $minRange.val(value);
                updateProgress();
            });

            $maxInput.on('input', function() {
                const value = Math.max(parseInt($(this).val()), parseInt($minInput.val()) + 1);
                $(this).val(value);
                $maxRange.val(value);
                updateProgress();
            });

            // 筛选按钮
            $('.btn-filter-price').on('click', function() {
                ShopFilter.applyFilters();
            });

            // 初始化进度条
            updateProgress();
        },

        // 分类筛选
        setupCategoryFilter: function() {
            $(document).on('change', 'input[data-category]', function() {
                ShopFilter.applyFilters();
            });
        },

        // 排序筛选
        setupSortFilter: function() {
            $('.woocommerce-ordering select').on('change', function() {
                ShopFilter.applyFilters();
            });
        },

        // 视图切换
        setupViewToggle: function() {
            $('.view-mode').on('click', function(e) {
                e.preventDefault();
                
                $('.view-mode').removeClass('active');
                $(this).addClass('active');
                
                const viewType = $(this).data('view');
                const $productsContainer = $('.collection-products ul.products');
                
                if (viewType === 'list') {
                    $productsContainer.addClass('list-view');
                } else {
                    $productsContainer.removeClass('list-view');
                }
                
                // 保存视图偏好
                localStorage.setItem('wbw_view_preference', viewType);
            });

            // 恢复视图偏好
            const savedView = localStorage.getItem('wbw_view_preference');
            if (savedView === 'list') {
                $('.view-mode[data-view="list"]').trigger('click');
            }
        },

        // 加载更多
        setupLoadMore: function() {
            $(document).on('click', '.load-more-products', function(e) {
                e.preventDefault();
                
                const $button = $(this);
                const page = parseInt($button.data('page')) + 1;
                
                $button.addClass('loading').text('Loading...');
                
                $.ajax({
                    url: wbw_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'wbw_load_more_products',
                        page: page,
                        nonce: wbw_ajax.nonce,
                        ...ShopFilter.getFilterData()
                    },
                    success: function(response) {
                        if (response.success && response.data.html) {
                            $('.collection-products ul.products').append(response.data.html);
                            $button.data('page', page);
                            
                            if (page >= response.data.max_pages) {
                                $button.hide();
                            }
                        }
                        
                        $button.removeClass('loading').text('Load More');
                    }
                });
            });
        },

        // 移动端筛选切换
        setupFilterToggle: function() {
            $('.filter-toggle').on('click', function() {
                $('.collection-sidebar').toggleClass('show');
                $('body').toggleClass('filter-open');
            });

            $('.filter-close, .filter-overlay').on('click', function() {
                $('.collection-sidebar').removeClass('show');
                $('body').removeClass('filter-open');
            });
        },

        // 应用筛选
        applyFilters: function() {
            const filterData = this.getFilterData();
            
            // 显示加载状态
            $('.collection-products').addClass('loading');
            
            $.ajax({
                url: wbw_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'wbw_filter_products',
                    nonce: wbw_ajax.nonce,
                    ...filterData
                },
                success: function(response) {
                    if (response.success) {
                        $('.collection-products ul.products').html(response.data.html);
                        ShopFilter.updateResultsCount(response.data.found_posts);
                        ShopFilter.updateURL(filterData);
                    }
                    
                    $('.collection-products').removeClass('loading');
                },
                error: function() {
                    $('.collection-products').removeClass('loading');
                    alert('Failed to filter products. Please try again.');
                }
            });
        },

        // 获取筛选数据
        getFilterData: function() {
            const data = {};
            
            // 价格范围
            const minPrice = $('.min-input').val();
            const maxPrice = $('.max-input').val();
            if (minPrice) data.min_price = minPrice;
            if (maxPrice) data.max_price = maxPrice;
            
            // 选中的分类
            const selectedCategories = [];
            $('input[data-category]:checked').each(function() {
                selectedCategories.push($(this).data('category'));
            });
            if (selectedCategories.length > 0) {
                data.category = selectedCategories.join(',');
            }
            
            // 选中的品牌
            const selectedBrands = [];
            $('input[data-brand]:checked').each(function() {
                selectedBrands.push($(this).data('brand'));
            });
            if (selectedBrands.length > 0) {
                data.brand = selectedBrands.join(',');
            }
            
            // 排序
            const orderby = $('.woocommerce-ordering select').val();
            if (orderby) data.orderby = orderby;
            
            // 每页数量
            data.posts_per_page = 12;
            
            return data;
        },

        // 更新结果数量
        updateResultsCount: function(count) {
            $('.woocommerce-result-count').html(`Showing all ${count} results`);
        },

        // 更新URL（不刷新页面）
        updateURL: function(filterData) {
            const url = new URL(window.location);
            
            // 清除旧的筛选参数
            url.searchParams.delete('min_price');
            url.searchParams.delete('max_price');
            url.searchParams.delete('product_cat');
            url.searchParams.delete('orderby');
            
            // 添加新的筛选参数
            Object.keys(filterData).forEach(key => {
                if (filterData[key]) {
                    url.searchParams.set(key, filterData[key]);
                }
            });
            
            // 更新URL
            window.history.replaceState({}, '', url);
        },

        // 清除所有筛选
        clearAllFilters: function() {
            // 重置价格筛选
            $('.min-input').val($('.min-range').attr('min'));
            $('.max-input').val($('.max-range').attr('max'));
            $('.min-range').val($('.min-range').attr('min'));
            $('.max-range').val($('.max-range').attr('max'));
            $('.price-progress').css({ 'left': '0%', 'right': '0%' });
            
            // 取消选择所有复选框
            $('input[data-category], input[data-brand]').prop('checked', false);
            
            // 重置排序
            $('.woocommerce-ordering select').val('menu_order');
            
            // 应用筛选
            this.applyFilters();
        }
    };

    // 文档加载完成后初始化
    $(document).ready(function() {
        ShopFilter.init();
        
        // 清除筛选按钮
        $('.clear-filters').on('click', function(e) {
            e.preventDefault();
            ShopFilter.clearAllFilters();
        });
    });

    // 全局暴露
    window.ShopFilter = ShopFilter;

})(jQuery);

// CSS样式增强
const filterStyles = `
    .collection-products.loading {
        opacity: 0.5;
        pointer-events: none;
        position: relative;
    }

    .collection-products.loading::after {
        content: 'Loading...';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(255,255,255,0.9);
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        z-index: 10;
    }

    .price-range-slider {
        position: relative;
        margin: 20px 0;
    }

    .price-progress {
        height: 5px;
        background: #007cba;
        border-radius: 5px;
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    }

    .price-range-input {
        position: relative;
    }

    .price-range-input input {
        position: absolute;
        width: 100%;
        height: 5px;
        top: 50%;
        transform: translateY(-50%);
        background: none;
        pointer-events: none;
        appearance: none;
        -webkit-appearance: none;
    }

    .price-range-input input::-webkit-slider-thumb {
        height: 20px;
        width: 20px;
        border-radius: 50%;
        background: #007cba;
        pointer-events: auto;
        appearance: none;
        -webkit-appearance: none;
        cursor: pointer;
    }

    .price-range-input input::-moz-range-thumb {
        height: 20px;
        width: 20px;
        border-radius: 50%;
        background: #007cba;
        pointer-events: auto;
        cursor: pointer;
        border: none;
    }

    @media (max-width: 768px) {
        .collection-sidebar {
            position: fixed;
            top: 0;
            left: -100%;
            width: 280px;
            height: 100vh;
            background: #fff;
            z-index: 9999;
            transition: left 0.3s ease;
            overflow-y: auto;
            padding: 20px;
        }

        .collection-sidebar.show {
            left: 0;
        }

        body.filter-open::after {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 9998;
        }
    }
`;

// 注入CSS样式
if (!document.getElementById('shop-filter-styles')) {
    const styleSheet = document.createElement('style');
    styleSheet.id = 'shop-filter-styles';
    styleSheet.textContent = filterStyles;
    document.head.appendChild(styleSheet);
}